package com.yoouce.patchmng.interceptor;

import com.yoouce.patchmng.init.SystemContants;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统过滤器
 * Created by Scott.Lee on 15-9-29.
 */
public class SystemGloableInterceptor extends HandlerInterceptorAdapter
{
    private List<String> excludeUrls;// 不需要拦截的资源
    
    /**
     * 请求前判断Session是否超时
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception
    {
        // 获取user Session对象
        Object userInfo = request.getSession()
                .getAttribute(SystemContants.USER_KEY);
                
        String requestUri = request.getRequestURI();
        
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        
        if (url.contains("assets") || url.contains("css")
                || url.contains("js")  || excludeUrls.contains(url))
        {// 如果要访问的资源是不需要验证的
            return true;
        }
        
        if (userInfo == null)
        {
            request.getRequestDispatcher("/login.jsp").forward(request,
                    response);
            return false;
        }
        else
        {
            return true;
        }
    }
    
    public void setExcludeUrls(List<String> excludeUrls)
    {
        this.excludeUrls = excludeUrls;
    }
    
}